/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package chconfig

import (
	"regexp"

	mb "git.cloud.inspur.com/ichain/ichain-protos-go/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/logging"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
)

var logger = logging.NewLogger("ichainsdk/ichain")

var versionCapabilityPattern = regexp.MustCompile(`^V(\d+(_\d+?)*)$`)

type ChainCfg struct {
	id           string
	blockNumber  uint64
	iams         []*mb.IAMConfig
	anchorInodes []*ichain.OrgAnchorInode
	consensers   []string
	versions     *ichain.Versions
	capabilities map[ichain.ConfigGroupKey]map[string]bool
}

func NewChainCfg(chainID string) *ChainCfg {
	return &ChainCfg{id: chainID}
}

func (cfg *ChainCfg) ID() string {
	return cfg.id
}

func (cfg *ChainCfg) BlockNumber() uint64 {
	return cfg.blockNumber
}

func (cfg *ChainCfg) IAMs() []*mb.IAMConfig {
	return cfg.iams
}

func (cfg *ChainCfg) AnchorInodes() []*ichain.OrgAnchorInode {
	return cfg.anchorInodes
}

func (cfg *ChainCfg) Consensers() []string {
	return cfg.consensers
}

func (cfg *ChainCfg) Versions() *ichain.Versions {
	return cfg.versions
}

func (cfg *ChainCfg) HasCapability(group ichain.ConfigGroupKey, capability string) bool {
	groupCapabilities, ok := cfg.capabilities[group]
	if !ok {
		return false
	}
	if groupCapabilities[capability] {
		return true
	}

	if isVersionCapability(capability) {
		for c := range groupCapabilities {
			if isVersionCapability(c) && c > capability {
				logger.Debugf("[%s] is greater than [%s] and therefore capability is supported", c, capability)
				return true
			}
		}
	}
	return false
}

func isVersionCapability(capability string) bool {
	return versionCapabilityPattern.MatchString(capability)
}
